using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using AForge;
using AForge.Controls;
using AForge.Video;
using AForge.Video.DirectShow;

namespace TimeCameraWinForm
{
  public partial class ShootForm : Form
  {
    FilterInfoCollection videoDevices;
    VideoCaptureDevice videoSource;
    Bitmap img;
    public ShootForm()
    {
      InitializeComponent();
      videoDevices = new FilterInfoCollection(FilterCategory.VideoInputDevice);
      if (videoDevices.Count == 0)
      {
        MessageBox.Show("无可用摄像头");
        this.Close();
      }
      videoSource = new VideoCaptureDevice(videoDevices[0].MonikerString);
      videoSourcePlayer1.VideoSource = videoSource;
      videoSourcePlayer1.Start();
      btn_save.Enabled = false;
      pictureBox1.SizeMode = PictureBoxSizeMode.StretchImage;
    }

    private void btn_shoot_Click(object sender, EventArgs e)
    {
      img = videoSourcePlayer1.GetCurrentVideoFrame();
      pictureBox1.Image = img;
      btn_save.Enabled = true;
    }

    private void btn_closeCamera_Click(object sender, EventArgs e)
    {
      if (videoSourcePlayer1.VideoSource != null)
      {
        videoSourcePlayer1.SignalToStop();
        videoSourcePlayer1.WaitForStop();
        videoSourcePlayer1.VideoSource = null;
      }
    }

    private void btn_save_Click(object sender, EventArgs e)
    {
      MemoryStream memoryStream = new MemoryStream();
      pictureBox1.Image.Save(memoryStream,ImageFormat.Png);
      Byte[] image = new byte[memoryStream.Length];
      memoryStream.Seek(0, SeekOrigin.Begin);
      memoryStream.Read(image, 0, image.Length);
      if (saveFileDialog1.ShowDialog(this) == DialogResult.OK)
      {
        saveFileDialog1.OpenFile().Write(image);
      }
    }
    private void ShootForm_FormClosed(object sender, FormClosedEventArgs e)
    {
      if (videoSourcePlayer1.VideoSource != null)
      {
        videoSourcePlayer1.SignalToStop();
        videoSourcePlayer1.WaitForStop();
        videoSourcePlayer1.VideoSource = null;
      }
    }
  }
}
